<template>
    <view class="operation-addr-main">
        <view class="item-mes">
            <view class="label">收货人</view>
            <input
                class="mes"
                placeholder-class="placeholder"
                :cursor-spacing="75"
                :maxlength="20"
                placeholder="请输入收货人姓名"
                v-model="Data.form.realName" />
        </view>
        <view class="item-mes">
            <view class="label">手机号</view>
            <input
                class="mes"
                placeholder-class="placeholder"
                :cursor-spacing="75"
                placeholder="请输入收货人手机号"
                type="number"
                :maxlength="11"
                v-model="Data.form.mobile" />
        </view>
        <view class="item-mes pr0">
            <view class="label">所在地区</view>
            <uni-data-picker
                ref="pickerRef"
                class="mes"
                placeholder="请选择省市区乡镇/街道"
                popup-title="请选择所在地区"
                :localdata="Data.dataTree"
                :map="{ text: 'name', value: 'id', code: 'id' }"
                @change="getAddrIds"
                :clear-icon="false"
                v-model="Data.form.area">
            </uni-data-picker>
            <view class="choose_box" @click="chooseAddr">
                <image src="/static/marker/dingwei_icon.png" class="choose-addr" />
            </view>
        </view>
        <view class="item-mes">
            <view class="label">详细地址</view>
            <input class="mes" placeholder-class="placeholder" placeholder="请输入详细地址" v-model="Data.form.addr" />
        </view>
        <view class="default-addr-container">
            <view>设为默认收货地址</view>
            <switch
                :checked="Data.form.isDefault === 1"
                @change="Data.form.isDefault = Data.form.isDefault === 1 ? 2 : 1"
                color="#FE292B" />
        </view>
        <view @click="saveAddr" :class="['save-addr', Data.canSave ? '' : 'disabled']">保存</view>
        <view v-if="addrType === 'edit'" @click="Data.delAddrShow = true" class="delete-addr">删除收货地址</view>
        <view class="popup-dialog" v-if="Data.delAddrShow">
            <view class="popup-dialog-content">
                <view class="title">确认删除该地址吗？</view>
                <view class="button">
                    <view class="cancel" @click="Data.delAddrShow = false">取消</view>
                    <view class="confirm" @click="delImgHandler">确认</view>
                </view>
            </view>
        </view>
        <!-- 隐私监听 -->
        <el-privacy-listener-popup></el-privacy-listener-popup>
    </view>
</template>
<script setup>
import { ref, reactive, watch, nextTick } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import router from '@/router';
import request from '@/request';
import store from '@/store';
import storage from '@/commons/storage';
import { isMobile, cloneDeep } from '@/commons/utils.js';

const orderStore = store.useOrderStore();

const props = defineProps({
    addrType: {
        default: 'add',
        type: String
    }
});

const Data = reactive({
    canSave: false,
    delAddrShow: false,
    dataTree: [],
    form: {
        realName: '',
        mobile: '',
        area: '',
        addr: '',
        isDefault: 2
    }
});
const pickerRef = ref(null);
uni.setNavigationBarTitle({
    title: props.addrType === 'edit' ? '编辑收货地址' : '添加收货地址'
});

const getPlace = () => {
    request('regionServ', { level: 4 }).then(res => {
        res.data.shift();
        orderStore.addressListLevel4 = res.data;
        Data.dataTree = orderStore.addressListLevel4;
    });
};
const initData = () => {
    Data.dataTree = orderStore.addressListLevel4;
    if (!Object.keys(Data.dataTree).length) {
        getPlace();
    }
    if (props.addrType === 'edit') {
        Data.form = cloneDeep(orderStore.editAddrMes);
        Data.form.provinceId = orderStore.editAddrMes.provinceId[0].id;
        Data.form.cityId = orderStore.editAddrMes.cityId[0].id;
        Data.form.areaId = orderStore.editAddrMes.areaId[0].id;
        Data.form.townId = orderStore.editAddrMes.townId[0] ? orderStore.editAddrMes.townId[0].id : '';
        Data.form.addr = orderStore.editAddrMes.street;
        Data.form.area = Data.form.townId ? Data.form.townId : Data.form.areaId;
    }
};
initData();
const getAddrIds = e => {
    const val = e.detail.value;
    Data.form.provinceId = val[0].value;
    Data.form.cityId = val[1]?.value;
    Data.form.areaId = val[2]?.value;
    Data.form.townId = val[3] ? val[3].value : '';
    nextTick(() => {
        Data.form.area = Data.form.townId || Data.form.areaId || Data.form.cityId || Data.form.provinceId;
    });
};
// 暂时不用
const getAddrObj = ({ title, id, key }) => {
    let target;
    JSON.stringify(Data.dataTree, (_, value) => {
        if (id == value[key] && title == value.name) {
            target = value;
            return;
        }
        return value;
    });
    return target;
};
const chooseAddr = () => {
    uni.chooseLocation({
        success: async res1 => {
            if (res1.name === '钓鱼岛') {
                let value = Data.dataTree.find(item => item.name === '钓鱼岛').id;

                getAddrIds(
                    reactive({
                        detail: {
                            value: [{ value }, { value: '' }, { value: '' }, { value: '' }]
                        }
                    })
                );
            } else {
                const res2 = await request('getMapTokenServ');
                if (res2.code != 0) return;
                const { token, client_id, client_secret } = res2.data;
                storage.set('ZW_LBS_TOKEN', token);
                storage.set('ZW_LBS_CLIENT_ID', client_id);
                storage.set('ZW_LBS_CLIENT_SECRET', client_secret);
                const { data } = await request('reverseAddressResolveServ', {
                    latitude: res1.latitude,
                    longitude: res1.longitude
                });
                let { ad_info } = data;
                let provCode = ad_info.city_code;
                let shengName = ad_info.province; //省、市
                let shiName = ad_info.city; //市
                let qvName = ad_info.district; //区
                let shengCode = provCode.substring(3, 5) + '0000'; //省
                let shiCode = provCode.substring(3, 9); // 市
                let quCode = ad_info.adcode; // 区
                // 详细地址
                // Data.form.addr = data.formatted_addresses?.recommend ?? res1.address;
                Data.form.addr = data.address_component.street_number;
                // 是否为直辖市
                let municipality = shengName === shiName;
                let shengObj = null;
                let shiObj = null;
                let qvObj = null;
                let obj = null;
                let { town } = data.address_reference;
                if (town) {
                    let id = town.id.substring(6, 9) + '000';
                    let title = town.title;
                    obj = getAddrObj({ title, id, key: 'town' });
                } else {
                    qvObj = getAddrObj({ title: qvName, id: quCode, key: 'code' });
                }
                if (!qvObj) {
                    shengObj = getAddrObj({ title: shengName, id: shengCode, key: 'code' });
                    shiObj = municipality
                        ? Data.dataTree.find(item => item.id == shengObj.id).children[0]
                        : getAddrObj({ title: shiName, id: shiCode, key: 'code' });
                }
                Data.form.area = obj?.id || qvObj?.id || shiObj?.id || shengObj?.id;
                nextTick(() => {
                    getAddrIds({
                        detail: {
                            value: pickerRef.value.inputSelected
                        }
                    });
                });
            }
        }
    });
};

watch(
    () => Data.form,
    val => {
        const { realName, addr, area, mobile } = val;
        Data.canSave = Boolean(realName && addr && area && mobile);
    },
    { immediate: true, deep: true }
);

const saveAddr = () => {
    const { mobile } = Data.form;
    if (!Data.canSave) {
        return;
    } else if (!isMobile(mobile)) {
        uni.showToast({
            title: !mobile ? '请输入手机号' : '手机号格式不正确',
            icon: 'none'
        });
    } else {
        const { realName, mobile, provinceId, cityId, areaId, townId, addr, isDefault, id } = Data.form;
        const params = {
            realName,
            mobile,
            provinceId,
            cityId,
            areaId,
            townId,
            street: addr,
            isDefault,
            wechat: 1
        };
        if (props.addrType === 'edit') {
            params.id = id;
            request('editAddressListServ', params).then(res => {
                router.back();
            });
        } else {
            request('saveAddressListServ', params).then(res => {
                router.back();
            });
        }
    }
};
// 删除收货地址
const delImgHandler = () => {
    request('deleteAddressListServ', { id: Data.form.id }).then(res => {
        router.back();
    });
};
</script>
<style lang="scss" src="./index.scss" scoped></style>
<style lang="scss">
.operation-addr-main {
    .item-mes {
        .placeholder {
            font-size: 29rpx;
            color: #cccccc;
        }
        .mes {
            .selected-item {
                width: auto;
            }
            .selected-item-active {
                border-bottom: 2px solid #fe292b;
            }
            .check {
                border: 2px solid #fe292b;
                border-left: 0;
                border-top: 0;
            }
            .uni-data-tree {
                .uni-data-tree-input {
                    .input-value-border {
                        border: 0 !important;
                        padding: 0;
                        .placeholder {
                            font-family: UICTFontTextStyleBody;
                            text-overflow: clip;
                            white-space: nowrap;
                            font-size: 29rpx !important;
                            color: #cccccc;
                        }
                    }
                    .arrow-area {
                        display: none !important;
                    }
                }
            }
        }
    }
}
</style>
